using UnityEngine;

[RequireComponent(typeof(AudioSource))]
public class LineAudio : MonoBehaviour
{
    public AudioClip clip;

    private AudioSource m_source;
    
    private void Start()
    {
        m_source = GetComponent<AudioSource>();
        Singleton<GameController>.Instance.OnGameStateChanged += OnStateChanged;
    }

    private void OnStateChanged(GameState state)
    {
        if (state == GameState.Playing)
        {
            Play(Singleton<GameController>.Instance.Time);
        }
        else
        {
            Stop();
        }
    }

    private void Stop()
    {
        if (m_source.isPlaying)
            m_source.Stop();
    }

    private void Play(float time)
    {
        if (!clip) return;
        m_source.clip = clip;
        m_source.Play();
        m_source.time = time;
    }
}
